﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using olierFrm.DataBase.FrameWork.StdQuery;
using olierFrm.WebFormDev.Session;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridView;
using olierFrm.DataBase.FrameWork;
using olierFrm.DataBase;
using olierFrm.Extensions.EString;
using olierFrm.Extensions.EDataTable;
using System.Drawing;
using DevExpress.Web.ASPxEditors;

namespace olierFrm.WebFormDev.StdQuery
{
    public class StdQuerySource
    {
        DataTable dtSource = null;
        StdQuerySQL dbStdQuery = null;
        public StdQuerySource(DataTable dtSource, StdQuerySQL dbStdQuery)
        {
            dtSource.BindCaptionToDataTable();
            this.dtSource = dtSource;
            this.dbStdQuery = dbStdQuery;
        }

        /// <summary>
        /// postback时在session对象中把分组字段增加、移除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ASPxGridView_BeforeColumnSortingGrouping(object sender, ASPxGridViewBeforeColumnGroupingSortingEventArgs e)
        {
            var grid = ((ASPxGridView)sender);
            var QueryName = grid.GetQueryName();
            if (e.Column.GroupIndex == -1)
                SGrid.RemoveGroup(QueryName, e.Column.FieldName);
            else
                SGrid.AddGroup(QueryName, e.Column.FieldName);
        }

        /// <summary>
        /// 绑定GridView
        /// </summary>
        /// <param name="grid"></param>
        private void BindGrid(ASPxGridView grid)
        {

            #region GRID的默认设置
            grid.SettingsPager.Summary.Text = "共{1}页，第{0}页（共{2}项）";
            grid.SettingsText.EmptyDataRow = "没有数据显示";
            grid.SettingsText.GroupPanel = "拖动列标题到此处进行分组";
            grid.SettingsText.GroupContinuedOnNextPage = "（续下页）";
            grid.SettingsLoadingPanel.Text = "数据加载中，请稍候！";


            //grid.SettingsPager.PrevPageButton.Text = "上一页";
            //grid.SettingsPager.NextPageButton.Text = "下一页";

            grid.Border.BorderStyle = BorderStyle.None;
            //grid.BorderBottom.BorderStyle = BorderStyle.Solid;
            grid.SettingsCookies.StoreGroupingAndSorting = true;
            //grid.Styles.Cell.Paddings.Padding = 1;
            //grid.Styles.DetailCell.Paddings.Padding = 1;
            //grid.Styles.Header.Paddings.Padding = 2;
            //grid.Styles.Footer.Paddings.Padding = 2;
            //grid.Styles.GroupPanel.Paddings.Padding = 3;
            //grid.Styles.PagerBottomPanel.Paddings.Padding = 0;
            grid.SettingsDetail.AllowOnlyOneMasterRowExpanded = true;
            grid.Settings.ShowHorizontalScrollBar = true;
            //grid.Width = 500;// new Unit("100%");
            grid.Styles.EmptyDataRow.BackColor = Color.Transparent;

            //grid.SettingsPager.PageSize = 30;
            grid.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;




            #endregion

            #region 处理隐藏字段
            var hfs = dbStdQuery.StdQuery.HideFields.Split(';').ToList();
            dtSource.AddHideColumn(hfs);

            #endregion

            grid.SetQueryName(dbStdQuery.StdQuery.QueryName);
            grid.DataSource = dtSource;

            #region 是否有SubQuery、是否显示合计、是否打开分组

            //是否打开分组
            if ((dbStdQuery.StdQuery.Property & 2) == 2)
            {
                grid.Settings.ShowGroupPanel = false;
            }
            else
                grid.Settings.ShowGroupPanel = true;



            //是否有SubQuery
            if (dbStdQuery.StdQuery.SubQuery != null && dbStdQuery.StdQuery.SubQuery.Trim().Length > 3)
            {
                SubQuery sq = new SubQuery(dbStdQuery.StdQuery.SubQuery);
                grid.SettingsDetail.ShowDetailRow = true;
                grid.KeyFieldName = dtSource.GetDataRowIndexFieldName();
                grid.DetailRowExpandedChanged += new ASPxGridViewDetailRowEventHandler(grid_DetailRowExpandedChanged);
                grid.Styles.DetailCell.Paddings.PaddingTop = 3;
            }
            //是否显示合计

            if (dbStdQuery.StdQuery.SumFields != null && dbStdQuery.StdQuery.SumFields.Trim().Length > 0 && dbStdQuery.StdQuery.SumFields != "*" && dtSource.Rows.Count != 0)
            {
                grid.Settings.ShowFooter = true;
                var fields = dbStdQuery.StdQuery.SumFields.Split(';').ToList();
                if (fields.IndexOf("*") != -1)
                {
                    //grid.TotalSummary.Add(new ASPxSummaryItem()
                    //{
                    //    FieldName = dtSource.Columns[0].ColumnName,
                    //    SummaryType = DevExpress.Data.SummaryItemType.Count,
                    //    DisplayFormat = "{0}",
                    //});
                    fields.Remove("*");
                }
                fields.Remove("");
                for (int i = 0; i < fields.Count; i++)
                {
                    grid.TotalSummary.Add(new ASPxSummaryItem()
                    {
                        FieldName = fields[i],
                        SummaryType = DevExpress.Data.SummaryItemType.Sum,
                        DisplayFormat = "{0}",
                    });
                }

            }
            #endregion

            grid.ClientSideEvents.ColumnSorting = "function (s,e){e.processOnServer = false;e.column.SortIndex += 1;}";
            //grid.ClientSideEvents.DetailRowExpanding = "function (s,e){alert(1);}";
            grid.BeforeColumnSortingGrouping += new ASPxGridViewBeforeColumnGroupingSortingEventHandler(ASPxGridView_BeforeColumnSortingGrouping);
            //grid.DataBound += new EventHandler(ASPxGridView_DataBound);

            grid.HtmlRowCreated += new ASPxGridViewTableRowEventHandler(grid_HtmlRowCreated);
            grid.Templates.Header = new HeaderRowTemplate();
            grid.Templates.DataItem = new DataItemTemplate();


        }

        void grid_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
        {

            if (e.RowType != GridViewRowType.Data) return;
            var grid = (ASPxGridView)sender;

            int curRowIndex = e.VisibleIndex;

            #region 行颜色
            if (dtSource.Columns.IndexOf("Color") != -1)
            {
                try
                {
                    string color = dtSource.Rows[curRowIndex]["Color"].ToString();

                    if (color.Length != 0)
                    {
                        //if (ColumnColor.ContainsKey(color)) color = ColumnColor[color];

                        if (color.Slice(0, 2).ToLower() == "cl")
                        {
                            e.Row.Style.Add("color", color.Substring(2));
                        }
                        else
                        {
                            string one = color.Substring(3, 2);
                            string two = color.Substring(5, 2);
                            string thr = color.Substring(7, 2);
                            //string name = UIFrm.BS.WebForm.Helper.colorHx16toRGB(color).Name;
                            e.Row.Style.Add("color", "#" + thr + two + one);
                        }
                    }
                }
                catch { }
            }
            #endregion

            #region 列显示多个Checkbox
            if (dtSource.ExtendedProperties.ContainsKey("PropCommon"))
            {
                var Prop = (List<string>)dtSource.ExtendedProperties["PropCommon"];
                foreach (var p in Prop)
                {
                    try
                    {
                        var propCommon = (List<WS_CommonItems>)dtSource.Columns[p].ExtendedProperties["PropCommon"];
                        e.Row.Cells[grid.Columns[p].VisibleIndex].Text = "";
                        foreach (var pc in propCommon)
                        {
                            ASPxCheckBox achk = new ASPxCheckBox() { Enabled = false };

                            var ps = Convert.ToInt32(dtSource.Rows[curRowIndex][p].ToString());
                            var comid = Convert.ToInt32(pc.sComID);

                            if ((ps & comid) == comid) achk.Checked = true;
                            //achk.Text = pc.sComDesc;

                            var hgc = new System.Web.UI.HtmlControls.HtmlGenericControl();
                            hgc.InnerHtml = pc.sComDesc;
                            e.Row.Cells[grid.Columns[p].VisibleIndex].Controls.Add(achk);
                            e.Row.Cells[grid.Columns[p].VisibleIndex].Controls.Add(hgc);
                        }
                    }
                    catch { }
                }
            }

            #endregion
        }

        /// <summary>
        /// 展开Grid时加载Detail的Template
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_DetailRowExpandedChanged(object sender, ASPxGridViewDetailRowEventArgs e)
        {
            var grid = (ASPxGridView)sender;
            grid.SetExpandRow(e.VisibleIndex);
            var it = new DetailRowTemplate();
            it.MasterStdQuery = dbStdQuery;
            it.MasterGrid = grid;
            grid.Templates.DetailRow = it;
        }

        /// <summary>
        /// 创建Grid
        /// </summary>
        /// <returns></returns>
        public ASPxGridView CreateGridView()
        {
            var grid = new ASPxGridView();
            //grid.EnableViewState = false;
            BindGrid(grid);

            grid.DataBind();
            grid.BindGroupToGrid();

            return grid;
        }

        /// <summary>
        /// 创建Grid，并绑定（执行DataBind方法）
        /// </summary>
        /// <returns></returns>
        public ASPxGridView CreateGridView(string ID)
        {
            var grid = new ASPxGridView();
            grid.ID = ID;
            grid.EnableViewState = false;
            BindGrid(grid);

            grid.DataBind();
            extensions(grid);
            return grid;
        }

        /// <summary>
        /// 创建Grid，并绑定（执行DataBind方法）
        /// </summary>
        /// <returns></returns>
        public ASPxGridView CreateGridView(string ID, int PageSize)
        {
            var grid = new ASPxGridView();
            grid.ID = ID;
            grid.EnableViewState = false;
            grid.Settings.ShowHorizontalScrollBar = grid.Settings.ShowVerticalScrollBar = true;

            grid.SettingsPager.PageSize = PageSize;
            BindGrid(grid);
            grid.DataBind();

            extensions(grid);
            return grid;
        }

        /// <summary>
        /// 绑定分组，隐藏字段，是否默认展开所有。
        /// </summary>
        /// <param name="grid"></param>
        public void extensions(ASPxGridView grid)
        {
            grid.BindGroupToGrid();
            grid.HideField();
            if ((dbStdQuery.StdQuery.Property & 4) == 4)
            {
                grid.ExpandAll();
            }
        }



        /// <summary>
        /// 创建Grid
        /// </summary>
        /// <returns></returns>
        public ASPxGridView CreateGridView(ASPxGridView grid)
        {
            BindGrid(grid);

            /*#region 处理隐藏字段
            var hfs = dtSource.GetHideColumn();
            //var hfs = dbStdQuery.StdQuery.HideFields.Split(';').ToList();
            hfs.Add(dtSource.GetDataRowIndexFieldName());
            hfs.Add("Color");
            foreach (var h in hfs)
            {
                if (grid.Columns[h] != null)
                    grid.Columns[h].Visible = false;
            }
            #endregion*/
            grid.DataBind();
            //grid.BindGroupToGrid();


            return grid;
        }


    }
}
